package com.simplehire.controller;

import com.simplehire.model.User;
import com.simplehire.model.UserRole;
import com.simplehire.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {
    
    private final UserService userService;
    
    public AdminController(UserService userService) {
        this.userService = userService;
    }
    
    // 用户管理主页
    @GetMapping("/users")
    public String userManagement(Model model, Authentication authentication) {
        List<User> users = userService.findAllUsers();
        model.addAttribute("users", users);
        model.addAttribute("currentUser", userService.findByUsername(authentication.getName()));
        return "admin/users";
    }
    
    // 编辑用户页面
    @GetMapping("/users/edit/{id}")
    public String editUserForm(@PathVariable Long id, Model model) {
        User user = userService.findById(id);
        if (user == null) {
            return "redirect:/admin/users?error=用户不存在";
        }
        model.addAttribute("user", user);
        model.addAttribute("allRoles", Arrays.asList(UserRole.values()));
        return "admin/edit-user";
    }
    
    // 更新用户信息
    @PostMapping("/users/update")
    public String updateUser(@ModelAttribute User user, 
                            @RequestParam(value = "roles", required = false) List<String> roleNames,
                            RedirectAttributes redirectAttributes) {
        
        User existingUser = userService.findById(user.getId());
        if (existingUser == null) {
            redirectAttributes.addFlashAttribute("error", "用户不存在");
            return "redirect:/admin/users";
        }
        
        try {
            // 更新基本信息
            existingUser.setFullName(user.getFullName());
            existingUser.setEmail(user.getEmail());
            existingUser.setPhoneNumber(user.getPhoneNumber());
            existingUser.setIsActive(user.getIsActive());
            
            // 更新角色
            if (roleNames != null) {
                List<UserRole> roles = roleNames.stream()
                        .map(UserRole::valueOf)
                        .collect(Collectors.toList());
                existingUser.setRoles(roles);
            }
            
            userService.updateUser(existingUser);
            redirectAttributes.addFlashAttribute("success", "用户更新成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
    
    // 删除用户
    @PostMapping("/users/delete/{id}")
    public String deleteUser(@PathVariable Long id, Authentication authentication, RedirectAttributes redirectAttributes) {
        User currentUser = userService.findByUsername(authentication.getName());
        if (currentUser.getId().equals(id)) {
            redirectAttributes.addFlashAttribute("error", "不能删除自己的账户");
            return "redirect:/admin/users";
        }
        
        try {
            userService.deleteUser(id);
            redirectAttributes.addFlashAttribute("success", "用户删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
    
    // 重置用户密码
    @PostMapping("/users/reset-password/{id}")
    public String resetPassword(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            userService.resetPassword(id, "123"); // 默认密码
            redirectAttributes.addFlashAttribute("success", "密码已重置为123");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "重置密码失败: " + e.getMessage());
        }
        
        return "redirect:/admin/users";
    }
}